-module(vregister_service).
-include("rec_dec.hrl").
-include_lib("stdlib/include/qlc.hrl").
-define(TAB,v_register_rec).
-export([start/0,addchange/1,get/0,get/1,delete/1]).

start() ->
	case db_mgr:check_table(?TAB) of
	no_found ->
		error_logger:warning_msg("create db table for (~s) with result:~p",
			[?MODULE,
			db_mgr:create_table(?TAB,record_info(fields,?TAB))]),
		ok;
	_ ->
		ok
	end.

addchange(Rec) when is_record(Rec,?TAB) ->
	case Rec#?TAB.id of
	"" ->
		add(Rec);
	_ ->
		modify(Rec)
	end.


add(Rec) when is_record(Rec,?TAB) ->
	Id = gen_server:call(couch_uuids,create),
	modify(Rec#?TAB{id=Id}).
	

modify(Rec) when is_record(Rec,?TAB) ->
	db_mgr:write(?TAB,Rec).
	
get() -> %% get all vendor info
	db_mgr:get(?TAB). 

get({id,Id}) ->
	Qry = qlc:q([X||X <- mnesia:table(?TAB),X#?TAB.id =:= Id]),
	db_mgr:do_transaction(fun() -> qlc:e(Qry) end);

get({mobile,Mobile}) ->
	Qry = qlc:q([X||X <- mnesia:table(?TAB),X#?TAB.mobile =:= Mobile]),
	db_mgr:do_transaction(fun() -> qlc:e(Qry) end).
delete(Id) ->
	lists:foreach(fun(E) ->
					vendor_service:delete(E#vendor_rec.id)
				  end,
				  vendor_service:get({register,Id})),
	del(Id).
del(ID) ->
	db_mgr:del(?TAB,ID).